import React, { useState, useEffect, useRef } from 'react'
import { Play, Save, Trash2, History, Database, Table, Code, Settings, Download, Copy, Info, Activity, Zap } from 'lucide-react'
import toast from 'react-hot-toast'
import { ksqlApi, KsqlQueryRequest, KsqlQueryResult } from '@/services/settings'
import { useKafkaStore } from '@/stores/kafkaStore'
import { useWebSocket } from '@/hooks/useWebSocket'

interface KsqlQuery {
  id: string
  name: string
  query: string
  timestamp: number
}

// 使用从services导入的接口
type KsqlResult = KsqlQueryResult

interface KsqlConfig {
  ksql_server_url: string
  ksql_username: string
  ksql_password: string
  ksql_timeout: number
  ksql_enabled: boolean
}

export default function KsqlBrowser() {
  const [query, setQuery] = useState('')
  const [results, setResults] = useState<KsqlResult | null>(null)
  const [loading, setLoading] = useState(false)
  const [savedQueries, setSavedQueries] = useState<KsqlQuery[]>([])
  const [showSaveDialog, setShowSaveDialog] = useState(false)
  const [queryName, setQueryName] = useState('')
  const [ksqlConfig, setKsqlConfig] = useState<KsqlConfig | null>(null)
  const [streams, setStreams] = useState<string[]>([])
  const [tables, setTables] = useState<string[]>([])
  const [serverInfo, setServerInfo] = useState<any>(null)
  const [healthStatus, setHealthStatus] = useState<any>(null)
  const [ksqlConnectionStatus, setKsqlConnectionStatus] = useState<'connected' | 'disconnected' | 'connecting'>('disconnected')
  const [isStreamQuery, setIsStreamQuery] = useState(false)
  const [streamResults, setStreamResults] = useState<any[]>([])
  const [streamQueryId, setStreamQueryId] = useState<string | null>(null)
  const textareaRef = useRef<HTMLTextAreaElement>(null)

  // WebSocket连接状态监听
  const { isConnected } = useWebSocket()

  // 根据WebSocket连接状态更新KSQL连接状态
  useEffect(() => {
    if (isConnected) {
      setKsqlConnectionStatus('connected')
    } else {
      setKsqlConnectionStatus('disconnected')
    }
  }, [isConnected])

  // 加载KSQL配置
  useEffect(() => {
    const savedConfig = localStorage.getItem('ksql_config')
    if (savedConfig) {
      try {
        const config = JSON.parse(savedConfig)
        setKsqlConfig(config)
        if (config.ksql_enabled) {
          loadServerInfo()
          loadHealthStatus()
          loadStreamsAndTables()
        }
      } catch (error) {
        console.error('加载KSQL配置失败:', error)
      }
    }

    // 加载保存的查询
    const saved = localStorage.getItem('ksql_saved_queries')
    if (saved) {
      try {
        setSavedQueries(JSON.parse(saved))
      } catch (error) {
        console.error('加载保存的查询失败:', error)
      }
    }
  }, [])

  // 加载服务器信息
  const loadServerInfo = async () => {
    try {
      setKsqlConnectionStatus('connecting')
      const info = await ksqlApi.getInfo()
      setServerInfo(info)
      setKsqlConnectionStatus('connected')
    } catch (error) {
      console.error('加载服务器信息失败:', error)
      setKsqlConnectionStatus('disconnected')
      // 优化错误信息显示
      if (error instanceof Error) {
        const message = error.message
        if (message.includes('404') || message.includes('Not Found')) {
          toast.error('KSQL服务器未找到，请检查服务器地址和端口')
        } else if (message.includes('Network Error') || message.includes('ECONNREFUSED')) {
          toast.error('无法连接到KSQL服务器，请检查服务器是否运行')
        } else if (message.includes('timeout')) {
          toast.error('连接KSQL服务器超时')
        } else {
          toast.error('KSQL服务器连接失败')
        }
      }
    }
  }

  // 加载健康状态
  const loadHealthStatus = async () => {
    try {
      const health = await ksqlApi.healthCheck()
      setHealthStatus(health)
      if (health.healthy) {
        setKsqlConnectionStatus('connected')
      } else {
        setKsqlConnectionStatus('disconnected')
      }
    } catch (error) {
      console.error('加载健康状态失败:', error)
      setKsqlConnectionStatus('disconnected')
    }
  }

  // 加载流和表列表
  const loadStreamsAndTables = async () => {
    try {
      // 获取流列表
      const streamsResponse = await ksqlApi.executeQuery({ ksql: 'SHOW STREAMS;' })
      console.log('流查询响应:', streamsResponse)

      if (streamsResponse.success && streamsResponse.data) {
        // 尝试多种可能的字段名
        const streamNames = streamsResponse.data.map((row: any) => {
          console.log('流数据行:', row)
          // 尝试各种可能的字段名
          return row.name || row.Name || row.STREAM_NAME || row['Stream Name'] ||
                 row.streamName || row.stream_name ||
                 // 如果是数组格式，取第一个元素
                 (Array.isArray(row) ? row[0] : null) ||
                 // 如果是对象，取第一个值
                 Object.values(row)[0]
        }).filter(Boolean)

        console.log('解析的流名称:', streamNames)
        setStreams(streamNames)
      } else {
        console.log('流查询失败或无数据:', streamsResponse)
        setStreams([])
      }

      // 获取表列表
      const tablesResponse = await ksqlApi.executeQuery({ ksql: 'SHOW TABLES;' })
      console.log('表查询响应:', tablesResponse)

      if (tablesResponse.success && tablesResponse.data) {
        // 尝试多种可能的字段名
        const tableNames = tablesResponse.data.map((row: any) => {
          console.log('表数据行:', row)
          // 尝试各种可能的字段名
          return row.name || row.Name || row.TABLE_NAME || row['Table Name'] ||
                 row.tableName || row.table_name ||
                 // 如果是数组格式，取第一个元素
                 (Array.isArray(row) ? row[0] : null) ||
                 // 如果是对象，取第一个值
                 Object.values(row)[0]
        }).filter(Boolean)

        console.log('解析的表名称:', tableNames)
        setTables(tableNames)
      } else {
        console.log('表查询失败或无数据:', tablesResponse)
        setTables([])
      }
    } catch (error) {
      console.error('加载流和表列表失败:', error)
      setStreams([])
      setTables([])
    }
  }

  // 检测是否为流查询
  const isStreamingQuery = (queryText: string): boolean => {
    const upperQuery = queryText.trim().toUpperCase()
    return upperQuery.includes('EMIT CHANGES') ||
           upperQuery.includes('EMIT FINAL') ||
           (upperQuery.startsWith('SELECT') && upperQuery.includes('FROM') && !upperQuery.includes('LIMIT'))
  }

  // 执行KSQL查询（保留用于兼容性，但使用新API）
  const executeKsqlQuery = async (queryText: string): Promise<KsqlResult> => {
    try {
      return await ksqlApi.executeQuery({ ksql: queryText })
    } catch (error: any) {
      return {
        success: false,
        error: error.message || '查询执行失败',
        execution_time: 0
      }
    }
  }

  // 执行查询
  const handleExecuteQuery = async () => {
    if (!query.trim()) {
      toast.error('请输入KSQL查询语句')
      return
    }

    if (!ksqlConfig || !ksqlConfig.ksql_enabled) {
      toast.error('请先在设置中启用并配置KSQL')
      return
    }

    setLoading(true)
    setResults(null)
    setStreamResults([])

    // 检测是否为流查询
    const isStreaming = isStreamingQuery(query)
    setIsStreamQuery(isStreaming)

    try {
      if (isStreaming) {
        // 对于流查询，显示提示信息
        toast.info('检测到流查询，将显示实时结果')
        setResults({
          success: true,
          data: [],
          row_count: 0,
          execution_time: 0
        })

        // 启动流查询（这里简化处理，实际应该使用WebSocket或SSE）
        const result = await ksqlApi.executeQuery({ ksql: query })
        if (result.success) {
          setStreamQueryId(result.query_id || 'stream_query')
          toast.success('流查询已启动')
        } else {
          toast.error('流查询启动失败')
          setResults(result)
        }
      } else {
        // 普通查询
        const result = await ksqlApi.executeQuery({ ksql: query })
        setResults(result)

        if (result.success) {
          toast.success(`查询执行成功，返回 ${result.row_count || 0} 行数据`)
        } else {
          toast.error('查询执行失败')
        }
      }
    } catch (error) {
      toast.error('查询执行失败')
    } finally {
      setLoading(false)
    }
  }

  // 停止流查询
  const handleStopStreamQuery = async () => {
    if (streamQueryId) {
      try {
        await ksqlApi.terminateQuery(streamQueryId)
        setIsStreamQuery(false)
        setStreamQueryId(null)
        setStreamResults([])
        toast.success('流查询已停止')
      } catch (error) {
        toast.error('停止流查询失败')
      }
    }
  }

  // 保存查询
  const handleSaveQuery = () => {
    if (!query.trim()) {
      toast.error('请输入查询语句')
      return
    }
    setShowSaveDialog(true)
  }

  const confirmSaveQuery = () => {
    if (!queryName.trim()) {
      toast.error('请输入查询名称')
      return
    }

    const newQuery: KsqlQuery = {
      id: Date.now().toString(),
      name: queryName,
      query: query,
      timestamp: Date.now()
    }

    const updated = [...savedQueries, newQuery]
    setSavedQueries(updated)
    localStorage.setItem('ksql_saved_queries', JSON.stringify(updated))
    
    setShowSaveDialog(false)
    setQueryName('')
    toast.success('查询保存成功')
  }

  // 加载保存的查询
  const loadSavedQuery = (savedQuery: KsqlQuery) => {
    setQuery(savedQuery.query)
    toast.success(`已加载查询: ${savedQuery.name}`)
  }

  // 删除保存的查询
  const deleteSavedQuery = (id: string) => {
    const updated = savedQueries.filter(q => q.id !== id)
    setSavedQueries(updated)
    localStorage.setItem('ksql_saved_queries', JSON.stringify(updated))
    toast.success('查询删除成功')
  }

  // 插入示例查询
  const insertSampleQuery = (sampleQuery: string) => {
    setQuery(sampleQuery)
  }

  // 复制结果
  const copyResults = () => {
    if (results && results.data) {
      const text = JSON.stringify(results.data, null, 2)
      navigator.clipboard.writeText(text)
      toast.success('结果已复制到剪贴板')
    }
  }

  // 示例查询 - 按类别分组
  const sampleQueries = {
    info: [
      { name: '显示流', query: 'SHOW STREAMS;', icon: '📊' },
      { name: '显示表', query: 'SHOW TABLES;', icon: '📋' },
      { name: '显示查询', query: 'SHOW QUERIES;', icon: '🔍' },
      { name: '显示连接器', query: 'SHOW CONNECTORS;', icon: '🔗' },
      { name: '显示函数', query: 'SHOW FUNCTIONS;', icon: '⚡' },
      { name: '显示属性', query: 'SHOW PROPERTIES;', icon: '⚙️' }
    ],
    create: [
      {
        name: '创建流',
        query: `CREATE STREAM user_events (
  user_id VARCHAR,
  event_type VARCHAR,
  timestamp BIGINT
) WITH (
  KAFKA_TOPIC='user-events',
  VALUE_FORMAT='JSON'
);`,
        icon: '➕'
      },
      {
        name: '创建表',
        query: `CREATE TABLE user_profiles (
  user_id VARCHAR PRIMARY KEY,
  name VARCHAR,
  email VARCHAR
) WITH (
  KAFKA_TOPIC='user-profiles',
  VALUE_FORMAT='JSON'
);`,
        icon: '📝'
      }
    ],
    query: [
      {
        name: '窗口聚合',
        query: `SELECT
  user_id,
  COUNT(*) as event_count
FROM user_events
WINDOW TUMBLING (SIZE 1 MINUTE)
GROUP BY user_id
EMIT CHANGES;`,
        icon: '📈'
      },
      {
        name: '流表连接',
        query: `SELECT
  e.user_id,
  p.name,
  e.event_type
FROM user_events e
LEFT JOIN user_profiles p
  ON e.user_id = p.user_id
EMIT CHANGES;`,
        icon: '🔄'
      },
      {
        name: '过滤查询',
        query: `SELECT * FROM user_events
WHERE event_type = 'login'
EMIT CHANGES;`,
        icon: '🔎'
      }
    ]
  }

  if (!ksqlConfig || !ksqlConfig.ksql_enabled) {
    return (
      <div className="container mx-auto px-4 py-8">
        <div className="text-center">
          <Database className="w-16 h-16 text-gray-400 mx-auto mb-4" />
          <h2 className="text-2xl font-bold text-gray-900 mb-2">KSQL未启用</h2>
          <p className="text-gray-600 mb-4">
            请先在设置页面中启用并配置KSQL服务器连接
          </p>
          <a href="/settings" className="btn-primary">
            <Settings className="w-4 h-4 mr-2" />
            前往设置
          </a>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-8">
      <div className="text-center lg:text-left">
        <h1 className="text-3xl font-bold gradient-text mb-2">KSQL浏览器</h1>
        <p className="text-lg text-gray-600">执行KSQL查询和流处理操作，实时分析Kafka数据</p>
      </div>

      <div className="grid grid-cols-1 xl:grid-cols-4 gap-8">
        {/* 左侧：查询编辑器 */}
        <div className="xl:col-span-3 space-y-8">
          {/* 查询编辑器 */}
          <div className="card hover-lift">
            <div className="card-header">
              <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between space-y-4 lg:space-y-0">
                <div>
                  <h3 className="card-title">查询编辑器</h3>
                  <p className="card-description">编写和执行KSQL查询语句</p>
                </div>
                <div className="flex flex-wrap gap-3">
                  <button
                    onClick={handleSaveQuery}
                    className="btn-outline hover-lift"
                  >
                    <Save className="w-4 h-4 mr-2" />
                    保存查询
                  </button>
                  {isStreamQuery && streamQueryId ? (
                    <button
                      onClick={handleStopStreamQuery}
                      className="btn-secondary hover-lift bg-red-50 border-red-300 text-red-700 hover:bg-red-100"
                    >
                      <Zap className="w-4 h-4 mr-2" />
                      停止流查询
                    </button>
                  ) : (
                    <button
                      onClick={handleExecuteQuery}
                      disabled={loading || !query.trim()}
                      className="btn-primary hover-lift"
                    >
                      <Play className={`w-4 h-4 mr-2 ${loading ? 'animate-spin' : ''}`} />
                      {loading ? '执行中...' : '执行查询'}
                    </button>
                  )}
                </div>
              </div>
            </div>
            <div className="p-4">
              <textarea
                ref={textareaRef}
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                placeholder="输入KSQL查询语句..."
                className="w-full h-40 p-3 border border-gray-300 rounded-md font-mono text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              />
            </div>
          </div>

          {/* 查询结果 */}
          {results && (
            <div className="bg-white rounded-lg shadow-sm border">
              <div className="p-4 border-b">
                <div className="flex items-center justify-between">
                  <h3 className="text-lg font-semibold flex items-center">
                    查询结果
                    {isStreamQuery && (
                      <span className="ml-2 px-2 py-1 bg-blue-100 text-blue-800 text-xs rounded-full flex items-center">
                        <Zap className="w-3 h-3 mr-1" />
                        流查询
                      </span>
                    )}
                  </h3>
                  <div className="flex items-center space-x-4">
                    {results.success && (
                      <>
                        <span className="text-sm text-gray-600">
                          {isStreamQuery ? `${streamResults.length} 条实时数据` : `${results.row_count} 行 · ${results.execution_time}ms`}
                        </span>
                        <button
                          onClick={copyResults}
                          className="btn-secondary text-sm"
                        >
                          <Copy className="w-4 h-4 mr-1" />
                          复制
                        </button>
                      </>
                    )}
                  </div>
                </div>
              </div>
              <div className="p-4">
                {results.success ? (
                  isStreamQuery ? (
                    // 流查询结果显示
                    <div>
                      {streamResults.length > 0 ? (
                        <div className="space-y-4">
                          <div className="flex items-center justify-between">
                            <span className="text-sm text-gray-600">实时数据流 (最新50条)</span>
                            <button
                              onClick={() => setStreamResults([])}
                              className="text-sm text-gray-500 hover:text-gray-700"
                            >
                              清空
                            </button>
                          </div>
                          <div className="max-h-96 overflow-y-auto border rounded">
                            {streamResults.slice(-50).map((row, index) => (
                              <div key={index} className={`p-3 border-b last:border-b-0 ${index % 2 === 0 ? 'bg-gray-50' : 'bg-white'}`}>
                                <div className="text-xs text-gray-500 mb-1">
                                  {new Date().toLocaleTimeString()}
                                </div>
                                <div className="font-mono text-sm">
                                  {typeof row === 'object' ? JSON.stringify(row, null, 2) : String(row)}
                                </div>
                              </div>
                            ))}
                          </div>
                        </div>
                      ) : (
                        <div className="text-center py-8">
                          <Zap className="w-12 h-12 text-blue-400 mx-auto mb-4" />
                          <p className="text-gray-500">流查询已启动，等待实时数据...</p>
                          <p className="text-sm text-gray-400 mt-2">数据将在此处实时显示</p>
                        </div>
                      )}
                    </div>
                  ) : (
                    // 普通查询结果显示
                    results.data && results.data.length > 0 ? (
                      <div className="overflow-x-auto">
                        <table className="w-full text-sm">
                          <thead>
                            <tr className="border-b">
                              {Object.keys(results.data[0]).map((key) => (
                                <th key={key} className="text-left py-2 px-3 font-medium">
                                  {key}
                                </th>
                              ))}
                            </tr>
                          </thead>
                          <tbody>
                            {results.data.map((row, index) => (
                              <tr key={index} className={index % 2 === 0 ? 'bg-gray-50' : ''}>
                                {Object.values(row).map((value, i) => (
                                  <td key={i} className="py-2 px-3">
                                    {typeof value === 'object' ? JSON.stringify(value) : String(value)}
                                  </td>
                                ))}
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    ) : (
                      <div className="text-center py-8 text-gray-500">
                        查询执行成功，但没有返回数据
                      </div>
                    )
                  )
                ) : (
                  <div className="bg-red-50 border border-red-200 rounded-md p-4">
                    <div className="text-red-800 font-medium">查询执行失败</div>
                    <div className="text-red-600 text-sm mt-1">{results.error}</div>
                    {results.execution_time && (
                      <div className="text-red-500 text-xs mt-1">
                        执行时间: {results.execution_time}ms
                      </div>
                    )}
                  </div>
                )}
              </div>
            </div>
          )}
        </div>

        {/* 右侧：工具面板 */}
        <div className="space-y-6">
          {/* 服务器状态 */}
          <div className="bg-white rounded-lg shadow-sm border">
            <div className="p-4 border-b">
              <h3 className="text-lg font-semibold flex items-center">
                <Info className="w-5 h-5 mr-2" />
                服务器状态
              </h3>
            </div>
            <div className="p-4 space-y-3">
              {/* 连接状态 */}
              <div className="flex items-center justify-between">
                <span className="text-sm text-gray-600">连接状态</span>
                <div className="flex items-center">
                  <div className={`w-2 h-2 rounded-full mr-2 ${
                    ksqlConnectionStatus === 'connected' ? 'bg-green-500' :
                    ksqlConnectionStatus === 'connecting' ? 'bg-yellow-500 animate-pulse' :
                    'bg-red-500'
                  }`}></div>
                  <span className={`text-sm font-medium ${
                    ksqlConnectionStatus === 'connected' ? 'text-green-600' :
                    ksqlConnectionStatus === 'connecting' ? 'text-yellow-600' :
                    'text-red-600'
                  }`}>
                    {ksqlConnectionStatus === 'connected' ? '已连接' :
                     ksqlConnectionStatus === 'connecting' ? '连接中...' :
                     '未连接'}
                  </span>
                </div>
              </div>

              {healthStatus && (
                <div className="flex items-center justify-between">
                  <span className="text-sm text-gray-600">健康状态</span>
                  <span className={`text-sm font-medium ${
                    healthStatus.healthy ? 'text-green-600' : 'text-red-600'
                  }`}>
                    {healthStatus.healthy ? '健康' : '异常'}
                  </span>
                </div>
              )}
              {serverInfo && (
                <>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-gray-600">版本</span>
                    <span className="text-sm font-mono">
                      {serverInfo.KsqlServerInfo?.version || '未知'}
                    </span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-gray-600">服务器ID</span>
                    <span className="text-sm font-mono text-xs">
                      {serverInfo.KsqlServerInfo?.serverID || '未知'}
                    </span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-gray-600">Kafka集群</span>
                    <span className="text-sm font-mono text-xs">
                      {serverInfo.KsqlServerInfo?.kafkaClusterId || '未知'}
                    </span>
                  </div>
                </>
              )}
              <button
                onClick={() => {
                  loadServerInfo()
                  loadHealthStatus()
                }}
                className="w-full text-sm text-blue-600 hover:text-blue-800 flex items-center justify-center"
              >
                <Activity className="w-4 h-4 mr-1" />
                刷新状态
              </button>
            </div>
          </div>

          {/* 流和表 */}
          <div className="bg-white rounded-lg shadow-sm border">
            <div className="p-4 border-b">
              <div className="flex items-center justify-between">
                <h3 className="text-lg font-semibold">流和表</h3>
                <button
                  onClick={loadStreamsAndTables}
                  className="text-sm text-blue-600 hover:text-blue-800"
                >
                  <Activity className="w-4 h-4" />
                </button>
              </div>
            </div>
            <div className="p-3 space-y-3">
              <div>
                <h4 className="text-sm font-medium text-gray-700 mb-2 flex items-center">
                  <Database className="w-4 h-4 mr-1" />
                  流 ({streams.length})
                </h4>
                <div className="space-y-1 max-h-32 overflow-y-auto">
                  {streams.length === 0 ? (
                    <div className="text-xs text-gray-500 italic">暂无流</div>
                  ) : (
                    streams.map((stream) => (
                      <div
                        key={stream}
                        className="text-xs text-blue-600 hover:text-blue-800 cursor-pointer p-1 hover:bg-blue-50 rounded truncate"
                        onClick={() => insertSampleQuery(`DESCRIBE ${stream};`)}
                        title={`点击查看流 ${stream} 的详细信息`}
                      >
                        {stream}
                      </div>
                    ))
                  )}
                </div>
              </div>

              <div>
                <h4 className="text-sm font-medium text-gray-700 mb-2 flex items-center">
                  <Table className="w-4 h-4 mr-1" />
                  表 ({tables.length})
                </h4>
                <div className="space-y-1 max-h-32 overflow-y-auto">
                  {tables.length === 0 ? (
                    <div className="text-xs text-gray-500 italic">暂无表</div>
                  ) : (
                    tables.map((table) => (
                      <div
                        key={table}
                        className="text-xs text-green-600 hover:text-green-800 cursor-pointer p-1 hover:bg-green-50 rounded truncate"
                        onClick={() => insertSampleQuery(`DESCRIBE ${table};`)}
                        title={`点击查看表 ${table} 的详细信息`}
                      >
                        {table}
                      </div>
                    ))
                  )}
                </div>
              </div>
            </div>
          </div>

          {/* 示例查询 */}
          <div className="bg-white rounded-lg shadow-sm border">
            <div className="p-3 border-b">
              <h3 className="text-base font-semibold flex items-center">
                <Code className="w-4 h-4 mr-2" />
                示例查询
              </h3>
            </div>
            <div className="p-3 space-y-3">
              {/* 信息查询 */}
              <div>
                <h4 className="text-xs font-medium text-gray-600 mb-2 flex items-center">
                  <span className="w-2 h-2 bg-blue-500 rounded-full mr-2"></span>
                  信息查询
                </h4>
                <div className="grid grid-cols-2 gap-1">
                  {sampleQueries.info.map((sample, index) => (
                    <button
                      key={index}
                      onClick={() => insertSampleQuery(sample.query)}
                      className="text-left text-xs text-blue-600 hover:text-blue-800 hover:bg-blue-50 p-2 rounded border border-blue-100 hover:border-blue-200 transition-colors"
                      title={sample.query}
                    >
                      <div className="flex items-center">
                        <span className="mr-1">{sample.icon}</span>
                        <span className="truncate">{sample.name}</span>
                      </div>
                    </button>
                  ))}
                </div>
              </div>

              {/* 创建语句 */}
              <div>
                <h4 className="text-xs font-medium text-gray-600 mb-2 flex items-center">
                  <span className="w-2 h-2 bg-green-500 rounded-full mr-2"></span>
                  创建语句
                </h4>
                <div className="space-y-1">
                  {sampleQueries.create.map((sample, index) => (
                    <button
                      key={index}
                      onClick={() => insertSampleQuery(sample.query)}
                      className="w-full text-left text-xs text-green-600 hover:text-green-800 hover:bg-green-50 p-2 rounded border border-green-100 hover:border-green-200 transition-colors"
                      title={sample.query}
                    >
                      <div className="flex items-center">
                        <span className="mr-1">{sample.icon}</span>
                        <span className="truncate">{sample.name}</span>
                      </div>
                    </button>
                  ))}
                </div>
              </div>

              {/* 查询语句 */}
              <div>
                <h4 className="text-xs font-medium text-gray-600 mb-2 flex items-center">
                  <span className="w-2 h-2 bg-orange-500 rounded-full mr-2"></span>
                  流处理查询
                </h4>
                <div className="space-y-1">
                  {sampleQueries.query.map((sample, index) => (
                    <button
                      key={index}
                      onClick={() => insertSampleQuery(sample.query)}
                      className="w-full text-left text-xs text-orange-600 hover:text-orange-800 hover:bg-orange-50 p-2 rounded border border-orange-100 hover:border-orange-200 transition-colors"
                      title={sample.query}
                    >
                      <div className="flex items-center">
                        <span className="mr-1">{sample.icon}</span>
                        <span className="truncate">{sample.name}</span>
                        <Zap className="w-3 h-3 ml-auto flex-shrink-0 text-orange-400" title="实时查询" />
                      </div>
                    </button>
                  ))}
                </div>
              </div>
            </div>
          </div>

          {/* 保存的查询 */}
          <div className="bg-white rounded-lg shadow-sm border">
            <div className="p-3 border-b">
              <h3 className="text-base font-semibold">保存的查询</h3>
            </div>
            <div className="p-2">
              {savedQueries.length === 0 ? (
                <div className="text-center py-3 text-gray-500 text-xs">
                  暂无保存的查询
                </div>
              ) : (
                <div className="space-y-1 max-h-40 overflow-y-auto">
                  {savedQueries.map((savedQuery) => (
                    <div key={savedQuery.id} className="flex items-center justify-between group hover:bg-gray-50 p-1 rounded">
                      <button
                        onClick={() => loadSavedQuery(savedQuery)}
                        className="flex-1 text-left text-xs text-blue-600 hover:text-blue-800 truncate min-w-0"
                        title={savedQuery.name}
                      >
                        <History className="w-3 h-3 inline mr-1 flex-shrink-0" />
                        <span className="truncate">{savedQuery.name}</span>
                      </button>
                      <button
                        onClick={() => deleteSavedQuery(savedQuery.id)}
                        className="text-red-500 hover:text-red-700 p-1 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0"
                        title="删除查询"
                      >
                        <Trash2 className="w-3 h-3" />
                      </button>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* 保存查询对话框 */}
      {showSaveDialog && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-96">
            <h3 className="text-lg font-semibold mb-4">保存查询</h3>
            <input
              type="text"
              value={queryName}
              onChange={(e) => setQueryName(e.target.value)}
              placeholder="输入查询名称"
              className="w-full p-3 border border-gray-300 rounded-md mb-4"
              autoFocus
            />
            <div className="flex justify-end space-x-3">
              <button
                onClick={() => setShowSaveDialog(false)}
                className="btn-secondary"
              >
                取消
              </button>
              <button
                onClick={confirmSaveQuery}
                className="btn-primary"
              >
                保存
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
